<?php
require_once 'phpmoko/lib/common.php';

class Cache
{

	static function begin()
	{
		ob_start();
		ob_implicit_flush(0);
	}

	static function end()
	{
		$contents = ob_get_contents();
		ob_end_clean();

		return $contents;
	}

	static private function checkCanGzip()
	{
		if (headers_sent() || (connection_status() != 0))
			return 0;

		if (!isset($_SERVER["HTTP_ACCEPT_ENCODING"]))
			return 0;

		if (strpos($_SERVER["HTTP_ACCEPT_ENCODING"], 'x-gzip') !== false)
			return "x-gzip";

		if (strpos($_SERVER["HTTP_ACCEPT_ENCODING"], 'gzip') !== false)
			return "gzip";

		return 0;
	}

	static function compressStream($stream, $level = 2)
	{
		$ENCODING = Cache::checkCanGzip();
		if ($ENCODING) {
			// $stream2 = '<p>Sin comprimir: ' . strlen($stream) . '<br>';
			// $stream2 .= 'Comprimido con gzcompress: ' . strlen(gzcompress($stream, $level)) . '<br>';
			// $stream .= $stream2;
			header('Content-Encoding: ' . $ENCODING);
			return "\x1f\x8b\x08\x00\x00\x00\x00\x00" . substr(gzcompress($stream, $level), 0, -4) . pack('V', crc32($stream)) . pack('V', strlen($stream));
		}

		return $stream;
	}

	static function endCompressed($level = 2)
	{
		$stream = ob_get_contents();
		ob_end_clean();

		return Cache::compressStream($stream, $level);
	}
}
?>